document.addEventListener('DOMContentLoaded', function() {
  const clearButton = document.getElementById('clearHistory');
  const tabList = document.getElementById('tabList');
  const emptyState = document.getElementById('emptyState');

  // 获取最近关闭的标签页
  function getRecentlyClosedTabs() {
    chrome.sessions.getRecentlyClosed({ maxResults: 25 }, function(sessions) {
      const tabs = sessions
        .filter(session => session.tab)
        .map(session => session.tab);
      
      chrome.storage.local.set({ closedTabs: tabs }, function() {
        loadTabs();
      });
    });
  }

  // 清空历史按钮事件
  clearButton.addEventListener('click', function() {
    // 只清除关闭的标签页数据，而不是清除所有存储
    chrome.storage.local.set({ closedTabs: [] }, function() {
      tabList.innerHTML = '';
      emptyState.style.display = 'block';
    });
  });

  // 加载标签列表
  function loadTabs() {
    chrome.storage.local.get(['closedTabs'], function(result) {
      const tabs = result.closedTabs || [];
      if (tabs.length === 0) {
        emptyState.style.display = 'block';
        return;
      }

      tabList.innerHTML = '';
      tabs.forEach(function(tab) {
        const li = createTabItem(tab);
        tabList.appendChild(li);
      });
    });
  }

  // 创建标签项
  function createTabItem(tab) {
    const li = document.createElement('li');
    li.className = 'tab-item';
    
    const img = document.createElement('img');
    img.className = 'tab-icon';
    img.src = tab.favIconUrl || 'icon.png';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'tab-content';
    
    const titleDiv = document.createElement('div');
    titleDiv.className = 'tab-title';
    titleDiv.textContent = tab.title;
    
    const urlDiv = document.createElement('div');
    urlDiv.className = 'tab-url';
    urlDiv.textContent = tab.url;
    
    contentDiv.appendChild(titleDiv);
    contentDiv.appendChild(urlDiv);
    
    li.appendChild(img);
    li.appendChild(contentDiv);
    
    li.addEventListener('click', function() {
      chrome.tabs.create({ url: tab.url });
    });
    
    return li;
  }

  // 初始加载
  getRecentlyClosedTabs();
  loadTabs();
});